<!DOCTYPE html>
<html lang="en">
<head>
    <?php
    unset($_SESSION['user']);
    ?>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>添加微信公众号</title>
  <script src="https://cdn.jsdelivr.net/npm/babel-polyfill/dist/polyfill.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/jquery"></script>
  <script src="__PUBLIC__/node_modules/mockjs/dist/mock-min.js"></script>
  <script src="__PUBLIC__/script/layer/layer.js"></script>
  <script src="__PUBLIC__/node_modules/datatables/media/js/jquery.dataTables.min.js"></script>
  <script src="__PUBLIC__/script/bootstrap-treeview-master/dist/bootstrap-treeview.min.js"></script>
  <link rel="stylesheet" href="__PUBLIC__/script/bootstrap-treeview-master/dist/bootstrap-treeview.min.css">
  <link rel="stylesheet" href="__PUBLIC__/node_modules/bootstrap/dist/css/bootstrap.min.css">
  <link rel="stylesheet" href="__PUBLIC__/style/manage.css">
  <link rel="stylesheet" href="__PUBLIC__/style/add_zizhanghao.css">
  <!-- 弹层 -->
  <script src="__PUBLIC__/script/layer/layer.js"></script>
</head>
<body>
  <!-- ajax地址 -->
  <input type="hidden" name = '发送随机密码' id = 'ajax_get_pass' value="{:U('Home/index/sms')}">

  <div class="container-fluid">
    <div class="row">
      <header class="col-xs-6 col-md-2 account_name"><img class='img-responsive' src="__PUBLIC__/images/logo_long.jpg" alt=""></header>
      <div class="col-xs-12 col-md-12">
        <div class="row">

          <!-- 左侧栏 -->
          <div class="col-md-2 manage_nav_box">
            <iframe src="{:U('nav_qudao')}?local=zizhanghao_a" frameborder="0" width="100%" style="height:12rem;"></iframe>
            <!-- 账号选项 -->
            <div class="account_option">
              <a href="{:U('index/update_passwd')}" class="pass_mod">修改密码</a>
              <a href="{:U('index/loginout')}" class="sign_out">退出登录</a>
            </div>
            <!-- end 账号选型 -->
          </div>
          <!-- end 左侧栏 -->

          <!-- 右主体  -->
          <div class="col-md-10 col-md-10 messageBox">
            <!-- begin 正常状态 -->
            <div class="form_box">
              <form autocomplete="off" action="{:U('Index/user_add')}" id="add_post" method="POST">
                <div style="display:none;">
                  <input type="hidden" value="{:U('Managezi/ajax_img')}" id='img_ajax_post'>
                  <input type="file" name="logo_file" id="logo_file" form='not_commit' accept="image/png, image/gif, image/jpeg, image/svg+xml">
                </div>
                <div id="logo_upload">
                  <!-- loginajax上传返回链接 -->
                  <input type="text" name="login_img" style="display: none;" value="" id='img_value' required>
                  <img src="__PUBLIC__/images/dengluye/u5.png" alt="logo" id="logo_preview">
                  <br>
                  <label for='logo_file' id="for_logo_file">点击上传LOGO</label>
                </div>
                <div class="shouquan_mail">
                  <input type="text" name="u_name" id="shouquan_name" placeholder="子账号名称" required>
                  <label id="for_add_his_qudao"><input type="checkbox" name="ck_qudao" id="add_his_qudao" value='1'>可以添加自己的渠道</label>
                </div>
                <div class="shouquan_mail">
                  <input type="text" name="u_phone" id="shouquan_phone" placeholder="授权手机号" required pattern="^(0|86|17951)?(13[0-9]|15[012356789]|17[0678]|18[0-9]|14[57])[0-9]{8}" onkeyup="value=value.replace(/[^\d]/g,'')" onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\d]/g,''))">
                  <label id = 'for_add_his_person'><input type="checkbox" name="ck_fenxiao" id="add_his_person" value='1'>可是使用分销功能</label>
                </div>
                <div class="shouquan_mail">
                  <input type="text" name="u_email" id="shouquan_mail" placeholder="邮箱" required>
                  <input type="text" value="3" style="display: none" name="u_type">
                  <label id = 'for_add_his_person'><input type="checkbox" name="ck_aj" id="must_add_his_person" value='0'>必须使用公用按揭员</label>
                </div>
                <div class="shouquan_mail">
                  <input type="text" name="u_pow_name" id="u_pow_name" placeholder="授权人" required>
                </div>
                <div class="shouquan_pass">
                  <input type="text" name="u_pass" id="shouquan_pass" placeholder="随机密码" required readonly>
                  <input type="button" id='send_auth_pass' value="密码">
                </div>
                <input type="submit" value="确定授权" id="add_post_button">
              </form>
            </div>
            <!-- end 正常状态 -->
            <!-- 只显示二维码 -->
            <div class="qr_box" style='display:none;'>
              <img id='anjie_qr_code' src="__PUBLIC__/qr_code.png" alt="10分钟有效二维码，关闭页面丢弃">
            </div>
            <!-- end 只显示二维码 -->
          </div>
          <!-- end 右主体 -->
        </div>
      </div>
    </div>
  </div>
  <script>
    $(document).ready(() => {
      $('#add_post_button').on('click', (event)=>{
        event.preventDefault();
        alert('请先获取密码！')
        return false
      })
      $('#send_auth_pass').one('click', send_pass)
    })
    function countDown (sec, ele, fn) {
      if ( typeof sec === 'number' && sec === 0) {
        fn()
      } else if (typeof sec === 'number' && sec > 0) {
        // 需要修改倒数的元素
        $(`#${ele}`).val(`${sec--}秒`)
        return ((sec, ele, fn) => {
          setTimeout(()=>{
            countDown(sec, ele, fn)
          }, 1000)
        })(sec, ele, fn)
      } else {
        ;
      }
    }
    // gen一个随机数值串出来
    function genRandCode (leng) {
      if( String(typeof leng).toLocaleLowerCase() === 'number') return Math.random().toFixed(leng).toString().replace(/\d\./, '')
      else {
        $('#getCode').one({'click': sendCode}, {id: 'getCode', urlID: 'url_getCode', phoneID: 'web_phone'})
        throw new Error(`收到类型不为数值的参数：${leng} | ${String(typeof leng).toLocaleLowerCase()}。无法产生指定长度随机数`)
      }
    }
    const send_code = genRandCode(8)
    function send_pass() {
        let url = $('#ajax_get_pass').val()
        let phone = $('#shouquan_phone').val()
        if (phone === '') {
          $('#send_auth_pass').off('click')
          $('#send_auth_pass').one('click', send_pass)
          alert('请先填写手机号');
        } else {
          $('#send_auth_pass').css('pointer-events','none')
          countDown(10, 'send_auth_pass', function(){
            $('#send_auth_pass').val('密码')
            $('#send_auth_pass').css('pointer-events','unset')
            $('#send_auth_pass').off('click')
            $('#send_auth_pass').one('click', send_pass)
          })

          $.ajax({
            url: url,
            // async: false,
            data: {mobile: phone, send_code: send_code},
            method: 'post',
            beforeSend: () => {
              layer.msg('正在发送密码，请稍候')
            }
          }).done((data, code)=> {
            layer.closeAll()

            if(data.send_code === `${send_code}` && Number(data.code) === 2) {
              $('#send_auth_pass').remove()
              $('#shouquan_pass').val(data.send_code)
              $('#add_post_button').off('click')

              $('#add_post_button').on('click', function (event) {
                event.preventDefault();
                $('input:required').each((index, item)=>{
                  if($(item).val() === '') {
                    alert('未填写完毕相关表单')
                    throw new Error('未填写完毕相关表单')
                  }
                })
                var formData = $('#add_post').serializeArray()
                var URLAll = "{:U('Index/user_add')}";
                $.ajax({
                  type: 'POST',
                  url: URLAll,
                  data: formData,
                  timeout: 30000,
                  beforeSend: () => {
                    layer.msg('正在提交数据，请稍候')
                  },
                  success:function(res){
                    console.log(res);
                    if(String(res.code) == '1'){
                      const isQrcode = $('#must_add_his_person').prop('checked')
                      if (isQrcode) {
                        if (!res.data) throw new Error(`未找到返回数据的连接：${res.code}`)
                        $(`#anjie_qr_code`).attr('src', res.data)
                        $(`.form_box`).remove()
                        $(`.qr_box`).css(`display`, 'block')
                      } else {
                        location.href = './manage_zizhanghao.html'
                      }
                    }
                  }
                })
                return false
              })
            } else {
              $('#send_auth_pass').off('click')
              $('#send_auth_pass').one('click', send_pass)
              window.alert(`网络错误，请重试。服务器提示：${data.msg}`)
            }
          })

        }

    }
    window.addEventListener('message', fromNav, false)
    function fromNav(event) {
      console.log(event.data.url)
      if (event.data.url.length && event.data.url.length > 1) {
        self.location = event.data.url
      }
    }
    </script>
    <script id = 'mock'>
      Mock.mock(/test.com\/send/, function (options) {
        return options
      })
    </script>
    <script id = 'async_logo'>
      $('#logo_file').on('change', function() {
        let fd = new FormData()
        fd.append("file", $("#logo_file").get(0).files[0])
        $.ajax($('#img_ajax_post').val(), {
          method: 'POST',
          data: fd,
          // 告诉jQuery不要去处理发送的数据
          processData : false,
          // 告诉jQuery不要去设置Content-Type请求头
          contentType : false,
          async: false,
          beforeSend:function(){
            alert("正在进行，请稍候");
          },
          success : function(responseStr) {
            layer.closeAll()
            if(String(responseStr.code) === '1'){
              // $('#logo_preview').attr('src', responseStr.message)
              $('#logo_preview').attr('src', '__ROOT__/' + responseStr.message)
              $('#img_value').val(responseStr.message)
              // alert("成功" + responseStr.message);
            } else{
              alert("上传失败，请重新选择图片并上传！");
            }
          },
          error : function(responseStr) {
            layer.closeAll()
            console.log("error");
          }
        })
      })
    </script>
</body>
</html>
